import { ref, watch } from 'vue'

/**
 * 本地存储 Hook
 * 
 * @param {string} key - 存储键名
 * @param {any} defaultValue - 默认值
 * @param {object} options - 配置选项
 * @param {boolean} options.serialize - 是否序列化存储，默认 true
 * @param {string} options.storage - 存储类型，'localStorage' 或 'sessionStorage'，默认 'localStorage'
 * 
 * @returns {object} 返回存储相关方法和状态
 * @returns {Ref<any>} returns.value - 当前存储值
 * @returns {function} returns.setValue - 设置新值
 * @returns {function} returns.remove - 移除存储项
 * @returns {function} returns.clear - 清空所有存储
 * 
 * @example
 * // 基础用法
 * const { value, setValue, remove } = useLocalStorage('user', { name: 'Guest' })
 * 
 * // 简单值存储
 * const { value: theme, setValue: setTheme } = useLocalStorage('theme', 'light')
 * 
 * // 使用 sessionStorage
 * const { value: tempData } = useLocalStorage('temp', null, { storage: 'sessionStorage' })
 * 
 * // 在模板中使用
 * <template>
 *   <div>
 *     <p>用户名: {{ value.name }}</p>
 *     <button @click="setValue({ name: 'Admin' })">设置管理员</button>
 *     <button @click="remove">清除用户</button>
 *   </div>
 * </template>
 * 
 * // 实际应用场景
 * const { value: settings, setValue: updateSettings } = useLocalStorage('app-settings', {
 *   theme: 'light',
 *   language: 'zh-CN',
 *   notifications: true
 * })
 * 
 * // 表单数据持久化
 * const { value: formData, setValue: saveForm } = useLocalStorage('draft-form', {})
 */
export function useLocalStorage(key, defaultValue = null, options = {}) {
  const { serialize = true, storage = 'localStorage' } = options
  
  const storageObj = storage === 'sessionStorage' ? sessionStorage : localStorage
  
  // 获取初始值
  function getStoredValue() {
    try {
      const item = storageObj.getItem(key)
      if (item === null) return defaultValue
      return serialize ? JSON.parse(item) : item
    } catch (error) {
      console.warn(`Failed to parse localStorage key "${key}":`, error)
      return defaultValue
    }
  }
  
  const value = ref(getStoredValue())
  
  // 设置值
  function setValue(newValue) {
    try {
      value.value = newValue
      if (serialize) {
        storageObj.setItem(key, JSON.stringify(newValue))
      } else {
        storageObj.setItem(key, String(newValue))
      }
    } catch (error) {
      console.warn(`Failed to save to localStorage key "${key}":`, error)
    }
  }
  
  // 移除存储项
  function remove() {
    storageObj.removeItem(key)
    value.value = defaultValue
  }
  
  // 清空所有存储
  function clear() {
    storageObj.clear()
    value.value = defaultValue
  }
  
  // 监听值变化，自动同步到存储
  watch(value, (newValue) => {
    if (newValue !== undefined) {
      setValue(newValue)
    }
  }, { deep: true })
  
  return {
    value,
    setValue,
    remove,
    clear
  }
} 